﻿using System;
using System.Threading;
using System.Windows.Forms;
using MovieBrowser.Controller;
using MovieBrowser.Event;
using MovieBrowser.Presentation.Events;
using ImdbBrowser;
using NymphsLib.WebBrowserController;

namespace MovieBrowser.Presentation.Browser
{
    public partial class MovieWebBrowser : UserControl, IDebugLogEvent, IMovieUpdateEvent
    {

        public MovieBrowserController Controller { get; set; }

        public string Html { get { return webBrowser1.DocumentText; } }

        public event EventHandler DebugText;
        private void InvokeOnDebugText(Exception exception)
        {
            var handler = DebugText;
            if (handler != null) handler(this, new DebugTextEventArgs(exception));
        }
        private void InvokeOnDebugText(string text)
        {
            var handler = DebugText;
            if (handler != null) handler(this, new DebugTextEventArgs(text));
        }

        public event EventHandler UpdateMovie;
        private void InvokeOnMovieUpdate(HtmlEventArgs e)
        {
            if (UpdateMovie != null) UpdateMovie(this, e);
        }

        public MovieWebBrowser()
        {
            InitializeComponent();
            webBrowser1.IntelligenceChanged += WebBrowser1IntelligenceChanged;
            //webBrowser1.AddDatabaseEvent += WebBrowser1AddDatabaseEvent;
            webBrowser1.UpdateNodeEvent += WebBrowser1UpdateNodeEvent;
        }

        void WebBrowser1IntelligenceChanged(object sender, ObjectEventArgs e)
        {
            Controller.IntelligentSearch = (bool)e.Data;
        }

        void WebBrowser1UpdateNodeEvent(object sender, EventArgs e)
        {
            InvokeOnMovieUpdate(new HtmlEventArgs(webBrowser1.DocumentText));
        }

        //void WebBrowser1AddDatabaseEvent(object sender, EventArgs e)
        //{
        //    InvokeOnMovieAdd(new HtmlEventArgs(webBrowser1.DocumentText));
        //}

        public void Navigate(string url)
        {
            webBrowser1.Navigate(url);
        }

        public void NavigateNew(string url)
        {
            webBrowser1.NavigateNew(url);
        }

        private void WebBrowser1DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                InvokeOnDebugText("Document Completed\r\n");
                if (Controller.RecentSearch && Controller.IntelligentSearch)
                    Controller.Redirect(e.Url.AbsoluteUri, webBrowser1.DocumentText);
                else
                {
                    Controller.RecentSearch = false;
                }
            }
            catch (Exception exception)
            {
                InvokeOnDebugText(exception);
            }
        }
    }
}
